
import wx
import wx.propgrid as wxpg

import ab_document
import ab_propgrid

import ab_ids as ai

from ab_config import Item


class EnvListDocFrameDocFrame(ab_document.DocumentFrame):
    def __init__(self, parent, app, hanlder, *args, **kws):
        ab_document.DocumentFrame.__init__(
            self, parent, app, hanlder, 'Environmental Variable Viewer')

        options = dict()
        template = {
            'Environment Variables': {
                'name': 'Environment Variable',
                'section': 'Environment',
                'options': options}
        }

        self.env = app.readKey(ai.CfgParaEnvObject)
        for key, item in (self.env.get() or dict()).items():
            if key:
                options[key] = {
                    'name': key,
                    'attr': item.getAttr(),
                    'value': item.getValue()
                }

        class _Reader:
            def getItem(self_, key):
                opt = options.get(key)
                if opt:
                    return Item(opt['name'], opt['attr'], opt['value'],
                                key=opt['name'], section='')

                return None

            def readKey(self_, key, escape=False):
                return self.env.get(key).getValue()

        self.prop = ab_propgrid.PropertyGrid(
            app, self, template, _Reader(), useOptionName=True)

        sizer = wx.BoxSizer()
        sizer.Add(self.prop, 1, wx.EXPAND, 0)
        self.SetSizer(sizer)

        self.prop.Bind(wxpg.EVT_PG_CHANGED, self.OnPropGridChange)
        self.setReady()

    def OnPropGridChange(self, event):
        p = event.GetProperty()
        if p:
            name = p.GetName()
            value = p.GetValueAsString()
            if name not in ('DATE', 'TIME') and value:
                self.env.set(name, value)


class EnvListDocFrameDocHandler(ab_document.DocumentHandler):
    def __init__(self):
        ab_document.DocumentHandler.__init__(
            self, 'envviewer', EnvListDocFrameDocFrame, True, False)
